package com.ss.web.tagmark.utils;

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.Stack;

import javax.naming.Context;
import javax.naming.InitialContext;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/**
 * 邮件发送类
 *
 * @author taofucheng
 *
 */
public class EmailSenderHelper {
	private static Logger logger = LoggerFactory.getLogger("sys");
	private static String HOST = "mail3.focuschina.com";
	private static String USERNAME = "abiz-beta@abiz.com";
	private static String PASSWORD = "mic66677777";
	private static String ENCODING = "UTF-8";
	private static String SENDER_MAIL = "noreply@aeps-assistant.com";
	private static String SENDER_NAME = "企业版自动运维平台";
	static {
		try {
			Context ctx = new InitialContext();
			Properties prop = (Properties) ctx.lookup("prjconf.ac");
			if (prop == null) {
				throw new IllegalArgumentException("JNDI中没有找到prjconf信息，无法初始化数据库。");
			}
			HOST = getProperty(prop, "mail.host", "mail.made-in-china.com");
			USERNAME = getProperty(prop, "mail.username", "caigou_dev@made-in-china.com");
			PASSWORD = getProperty(prop, "mail.password", "focustech2011");
		} catch (Exception e) {
		}
	}

	private static String getProperty(Properties prop, String key, String defaultValue) {
		String value = prop.getProperty(key);
		return StringUtils.defaultIfEmpty(value, defaultValue);
	}

	/**
	 * 发送邮件。
	 *
	 * @param subject
	 * @param content
	 * @param receiver
	 */
	public static void sendMail(String subject, String content, String... receiver) {
		HtmlEmail email = new HtmlEmail();
		try {
			// 这里是SMTP发送服务器的名字：163的如下："smtp.163.com"
			email.setHostName(HOST);
			// 字符编码集的设置
			email.setCharset(ENCODING);
			// 收件人的邮箱
			if (receiver != null && receiver.length > 0) {
				for (String r : receiver) {
					if (StringUtils.isBlank(r)) {
						continue;
					}
					email.addTo(r);
				}
			}
			// 发送人的邮箱
			email.setFrom(SENDER_MAIL, SENDER_NAME);
			// 如果需要认证信息的话，设置认证：用户名-密码。分别为发件人在邮件服务器上的注册名称和密码
			email.setAuthentication(USERNAME, PASSWORD);
			// 要发送的邮件主题
			email.setSubject(subject);
			// 要发送的信息，由于使用了HtmlEmail，可以在邮件内容中使用HTML标签
			email.setMsg(content);
			// 发送
			email.send();
		} catch (EmailException e) {
			logger.error("邮件发送失败！邮件的标题：【" + subject + "】，收件人：【" + JSON.toJSONString(receiver) + "】，内容：" + content, e);
		}
	}

	public static void main(String[] args) throws IOException {
		String json = FileUtils.readFileToString(new File("F:/tmp/data.json"), "UTF-8");
		json = json.replaceAll("\\\\*\"", "\"").replaceAll(",[ ]*\"", ",\"").replaceAll("\"[ ]*:[ ]*\"", "\":\"");
		StringBuffer html = new StringBuffer();
		for (int idx = json.indexOf(",\""); idx > -1; idx = json.indexOf(",\"")) {
			int _idx = json.indexOf("\":\"{\"");
			if (_idx > -1 && _idx < idx) {
				idx = _idx;
			}
			String pre = json.substring(0, idx + 1);
			int level = calcLevel(html + pre);
			if (html.length() > 0) {
				html.append("<br>");
			}
			for (int i = 0; i < (level - 1) * 4; i++) {
				html.append("&nbsp;");
			}
			String tmp = pre.startsWith(":\"{") ? pre.substring(2) : pre;
			if (tmp.indexOf("abiz-") > 0 && tmp.indexOf(".com") > 0) {
				tmp = "<font color='red'>" + tmp + "</font>";
			}
			html.append(tmp);
			json = json.substring(idx + 1);
		}
		if (json.length() > 0) {
			html.append("<br>");
			html.append(json);
		}
		sendMail("测试邮件", html.toString(), "taofucheng@made-in-china.com");
	}

	/**
	 * 计算层级
	 *
	 * @param str
	 * @return
	 */
	private static int calcLevel(String str) {
		Stack<Boolean> cache = new Stack<Boolean>();
		for (char c : str.toCharArray()) {
			if (c == '{') {
				cache.push(true);
			} else if (c == '}') {
				cache.pop();
			}
		}
		return cache.size();
	}
}
